import React from 'react'
import BasicMap from "./BasicMap";
import {Row, Col, Card, Tooltip, Button, Icon, Drawer, Table, Spin} from "antd";
import DeviceList from "./DeviceList";
import GridContent from '@/components/PageHeaderWrapper/GridContent';
import styles from './index.less';
import StayList from "./StayList";
import {fetchLatestStaysList, fetchStaysList, fetchTrailList} from "../../services/map";
import {secs2time, ts2time} from "../../utils/utils";
import DatePicker from "./DatePickerWrap";
import {STAY, TRAIL} from "../../config/const";
import moment from "moment";
import {connect} from "react-redux";
import {FETCH_DEVICES} from "../../models/device/const";
import {FormattedMessage} from "../../utils/locale";
import getDeviceList from "../../models/selectors";


const colResponsiveProps = {
  xl: 12,
  lg: 12,
  md: 12,
  sm: 24,
  xs: 24,
  style: {marginBottom: 24},
};

@connect(({device}) => {
  // console.log(device);
  //device 是个对象:从函数参数取出
  // device=device1;
  const deviceList = getDeviceList(device) || [];
  const deviceStatusMap = {};
  let deviceIdList = deviceList.map(item => (deviceStatusMap[item.device_id] = item.status, item.device_id)).sort();
  // deviceIdList=[100,200,300];
  return ({deviceList, deviceStatusMap, deviceIdList, deviceListFilter: device.deviceListFilter})
})

class Map extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      checkedKeys: [],
      stayList: [],
      trailList: [],
      infoWindowPosition: null,
      infoWindowText: '',
      cur_device: '',
      datePickerVisible: false,
      type: STAY,
      start_time: undefined,
      end_time: undefined,
      deviceListVisible: false,
      stayListVisible: true,
      selectDate: null,
      isTrail: false,
      deviceListFilter: '',
    };
    const {dispatch} = this.props;
    dispatch({
      type: FETCH_DEVICES,
    });
  }

  static getDerivedStateFromProps(props, state) {
    const {deviceIdList, deviceListFilter} = props;
    const deviceLength = deviceIdList.length;
    if (deviceLength > 0 && deviceListFilter !== state.deviceListFilter) {
      const checkedKeys = deviceIdList.map(item => ('' + item));
      return {deviceIdList, checkedKeys, deviceListFilter}
    }
    return null
  }


  componentDidMount() {
    this.getLatestStaysList();
  }

  getLatestStaysList = async () => {
    this.setState({loading: true});
    const stay_rsp = await fetchLatestStaysList();
    const _stayList = stay_rsp.data;
    const stayList = _stayList.map(item => (item.stay !== null && item.stay));
    const newState = {stayList, type: STAY, trailList: [], cur_device: '', isTrail: false, loading: false};
    const {deviceIdList} = this.state;
    let {checkedKeys} = this.state;
    if (checkedKeys.length === 1) {
      newState.checkedKeys = deviceIdList.map(item => ('' + item));
    }
    this.setState(state => (newState));
  };

  stayHandler = (stayList, checkedKeys) => {
    const marks = [],
      points = [];
    stayList.forEach(item => {
      if (!item) return;
      if (!checkedKeys.includes('' + item.deviceid)) return;
      const {id, selectedPoi, deviceid, starttime, endtime, recordtime} = item;
      const {late6, lnge6, address, name} = selectedPoi;
      const xy = {
        lng: lnge6 / 1e6,
        lat: late6 / 1e6
      };
      const point = {
        key: id,
        xy: [xy.lng, xy.lat],
        deviceid,
        starttime: ts2time(starttime, 'minute'),
        endtime: ts2time(endtime),
        staytime: secs2time((endtime - starttime) * 1000),
        recordtime,
        address,
        name
      };
      const mark = {xy, key: id};
      marks.push(mark);
      points.push(point);
    });

    return {marks, points}
  };

  handlerOk = (isFromMap = false) => (value) => {
    const start_time = Math.floor(value[0].valueOf() / 1e3);
    const end_time = Math.floor(value[1].valueOf() / 1e3);
    this.setState(
      {datePickerVisible: false, infoWindowPosition: null, selectDate: value},
      this.handleGetData({start_time, end_time}, isFromMap)
    )
  };

  handleGetData = ({start_time, end_time,}, isFromMap) => async () => {
    this.setState({loading: true});
    const {type, cur_device, checkedKeys,} = this.state;
    const params = {start_time, end_time,};
    let req = null;
    if (isFromMap) {
      req = {device_id: cur_device, params};
    } else {
      const devices = checkedKeys.map(device_id => (+device_id));
      req = {data: {devices}, params};
    }
    let trailList = [], stayList = [];
    if (type === TRAIL) {
      console.log(cur_device,params)

      const [staysRsp, trailRsp] = await Promise.all([fetchStaysList(req), fetchTrailList({device_id: cur_device, ...params})]);
      console.log(staysRsp,trailList)
      trailList = trailRsp.data;
      stayList = staysRsp.data;
    } else {
      const staysRsp = await fetchStaysList(req);
      stayList = staysRsp.data;
    }
    this.setState({start_time, end_time, trailList, stayList, isTrail: true, loading: false})
  };

  handleDeviceListVisible = () => {
    this.setState(({deviceListVisible, checkedKeys}) => ({
      deviceListVisible: !deviceListVisible,
      infoWindowPosition: null,
      infoWindowText: '',
      checkedKeys: deviceListVisible ? this.props.deviceIdList.map(item => ('' + item)) : checkedKeys,

    }))
  };
  /**
   * 点击面板触发事件
   */
  infoWindowHandler = (infoWindowPosition, info) => {
    //{lng: xy[0], lat: xy[1]参数{lng: 100, lat: 39}--- info 是这一行的信息
    const {xy, name, address, deviceid, starttime, endtime, staytime} = info;
    const infoWindowText = `
        <dl>
          <dt>设备序列号:</dt>
            <span>${deviceid}</span>
          <dt>地点:</dt>
            <span>${name}</span>
          <dt>地址:</dt>
            <span>${address}</span>
          <dt>到达时间:</dt>
            <span>${starttime}</span>
          <dt>离开时间:</dt>
            <span>${endtime}</span>
          <dt>停留时间:</dt>
            <span>${staytime}</span>
          <dt>坐标:</dt>
            <span>${xy}<span/>
        </dl>
        <a class=${TRAIL}>停留和轨迹</a>
        `;
    this.setState({
          infoWindowPosition,
          infoWindowText,
          cur_device: '' + deviceid
    })
  };

  setEventHandler = key => val => {
    if (key) {
      this.setState({[key]: val});
    } else {
      this.setState({...val})
    }
  };

  handleCheck = (val) => {
    this.setState({checkedKeys: val, infoWindowPosition: null})
  };

  handleStayListVisible = () => {
    // document.body.style.cssText = 'overflow:hidden;';
    this.setState(state => ({stayListVisible: !state.stayListVisible,}));
  };

  getDefaultDate = _ => [moment(), moment().add(1, 'days')];


  render() {
    const {checkedKeys, stayList, trailList, infoWindowPosition, infoWindowText, datePickerVisible, deviceListVisible, stayListVisible, selectDate, cur_device, isTrail, start_time, end_time, loading} = this.state;
    const {deviceIdList, deviceStatusMap,} = this.props;
    const {marks, points} = this.stayHandler(stayList, checkedKeys);

      //points是下面的智慧E谷
    const basicMapProps = {
      test:this.state.test,
      infoWindowPosition,
      infoWindowText,
      marks,
      points,
      trailList,
      checkedKeys,
      selectDate,
      cur_device,
      isTrail,
      deviceStatusMap,
      deviceListVisible,
      start_time,
      end_time,
      infoWindowHandler: this.infoWindowHandler,
      handleChangeState: this.setEventHandler(),
      getDefaultDate: this.getDefaultDate,
      getLatestStaysList: this.getLatestStaysList,
      onDeviceListVisible: this.handleDeviceListVisible,
      onOk: this.handlerOk(),
    };
    return (
      <div>
        <Spin spinning={loading} tip="获取数据中...">
          <BasicMap {...basicMapProps}/>
          <DatePicker
            onOk={this.handlerOk(true)}
            getDefaultDate={this.getDefaultDate}
            onSetVisible={this.setEventHandler('datePickerVisible')}
            visible={datePickerVisible}/>

          <DeviceList onCheck={this.handleCheck} deviceIdList={deviceIdList}
                      checkedKeys={checkedKeys} onVisible={this.handleDeviceListVisible}
                      visible={deviceListVisible}/>
          {/*<StayList points={points} infoWindowHandler={this.infoWindowHandler} visible={stayListVisible}*/}
          {/*          onClose={this.handleStayListVisible}/>*/}
        </Spin>
      </div>
    )
  }
}


export default Map;
